<template>
	<view class="body_page">
		<view :style="{ height: statusBarHeight + 'px', width: '100%', backgroundColor: 'transparent' }"></view>
		<view class="phone-display" element-loading-background="rgba(0, 0, 0, 0.7)">
			<div :id="`phone-display-container`">
			</div>
		</view>
	</view>
</template>

<script setup lang="ts">
	import '../../style/app.css'
	import { onLoad } from '@dcloudio/uni-app'
	type Machine = {
		id : number;
		ip : string;
		cpu : string;
		cpu_core : number;
		memory : number;
		volume : number;
		status : number;
		created_at : string;
		updated_at : string;
		mac_addr : string;
		volume_device : string;
	};

	type Instance = {
		id : number;
		machine_id : number;
		mac : string;
		ip : string;
		product_id : number;
		package_id : number;
		created_at : string;
		updated_at : string;
		status : number;
		is_realphone : number;
		adb_port : number;
		adb_address : string;
		height : number;
		width : number;
		image : string;
		image_tag : string;
		index : number;
		state : number;
		cpu_cores : number;
		memory : number;
		storage : number;
		name : string;
		machine : Machine;
	};

	type Phone = {
		id : number;
		user_id : string;
		instance_id : number;
		start_time : string;
		expire_time : string;
		status : number;
		created_at : string;
		updated_at : string;
		order_id : number;
		image : string;
		image_tag : string;
		auto_renew : number;
		screen_shot : string;
		instance_name : string;
		instances : Instance;
		checked ?: boolean;
		is_trial ?: number;
		state : number;
		screen_shot_loading ?: boolean;
	};
	let adb_host : string = ""
	let adb_port : string = ""
	let status_bar_height : number = 10
	let window_height : number = 100
	let window_width : number = 100
	let zoom : number = 0 //云手机缩放比例
	let zoom_width : number = 0 
	let zoom_height : number = 0
	let token : string = ""
	import { StreamClientScrcpy } from '../../app/googDevice/client/StreamClientScrcpy';
	import { ParamsStreamScrcpy } from '../../types/ParamsStreamScrcpy';
	import { ref, Ref, computed, onMounted, onUnmounted, watch, nextTick } from 'vue';
	import { useStore } from 'vuex';
	const statusBarHeight = ref(0);
	const store = useStore();
	const hash = '';
	const ws : Ref<WebSocket | null> = ref(null);
	const parsedQuery = new URLSearchParams(hash);
	const StreamClientScrcpy_start : Ref<StreamClientScrcpy | null> = ref(null);
	const initPhone = async (host : string, adb : string) => {
		// if (!phone.instances.machine || !phone.instances.adb_port) {

		// 	return;
		// }
		await initPlayers();
		const udid = `${host}:${adb}`;
		const wsUrl = `wss://ws.jtcloud.icu:10443/?action=proxy-adb&remote=tcp:8886&udid=${udid}`;
		console.log(process.env.UNI_PLATFORM)
		console.log('env:', process.env)
		if (process.env.UNI_PLATFORM === 'app') {
			// App 端用 uni.connectSocket
			uni.connectSocket({
				url: wsUrl,
				success() {
					console.log('uni.connectSocket 成功');
				},
				fail(err) {
					console.error('uni.connectSocket 出错', err);
				}
			});
			uni.onSocketOpen(() => {
				console.log('WebSocket连接成功 (uni)');
			});
			uni.onSocketError((err) => {});
		} else {
			// H5 端或其他平台，仍可用原生 WebSocket
			ws.value = new WebSocket(wsUrl);
			ws.value.onopen = () => {
				console.log('WebSocket连接成功');
			};
		};
		parsedQuery.set("action", "stream");
		parsedQuery.set("player", "mse");
		parsedQuery.set("udid", udid);
		parsedQuery.set("hostname", "ws.jtcloud.icu");
		parsedQuery.set("ws", wsUrl);
		parsedQuery.set("port", '10443');
		parsedQuery.set("secure", "true");
		console.log('213')
		StreamClientScrcpy_start.value = StreamClientScrcpy.start(parsedQuery);
		StreamClientScrcpy_start.value.setIdleThreshold(240000);
		// StreamClientScrcpy_start.value.addActivityListener(handleActivityChange);
		const player = StreamClientScrcpy_start.value?.getPlayer();
		console.log(player)
		setTimeout(()=>{
			if(player.videoWidth!=-1){
				console.log(player.videoWidth,player.videoHeight,zoom);
				console.log(player.videoWidth * zoom);
				document.documentElement.style.setProperty('--zoom_width',`${(player.videoWidth * zoom).toFixed(2)}px`)
				document.documentElement.style.setProperty('--zoom_height',`${(player.videoHeight * zoom).toFixed(2)}px`)
			}
		},500)
		const checkbox = document.getElementById(`input_capture_keyboard_${udid}_${player?.getName()}`) as HTMLInputElement | null;
		if (checkbox) {
			checkbox.checked = false;
			checkbox.dispatchEvent(new Event('change'));
		}
		StreamClientScrcpy_start.value?.setHandleKeyboardEvents(false);
	};
	const initPlayers = async () => {
		//const { TinyH264Player } = await import('@/app/player/TinyH264Player');
		const { MsePlayer } = await import('@/app/player/MsePlayer');
		//import {MsePlayer} from '@/app/player/MsePlayer';
		StreamClientScrcpy.registerPlayer(MsePlayer);
		// const { WebCodecsPlayer } = await import('@/app/player/WebCodecsPlayer');
		// StreamClientScrcpy.registerPlayer(WebCodecsPlayer);
		MsePlayer.resize(880, 1920, 1);
	};
	onLoad((options) => {
		console.log("options:", options)
		adb_host = options.adb_host
		adb_port = options.adb_port
		token = options.token
		status_bar_height = options.status_bar_height //手机顶部自带导航栏高度
		statusBarHeight.value = status_bar_height
		window_height = options.windows_height
		window_width = options.windows_width
		zoom= options.zoom
		zoom_width= (880 * options.zoom).toFixed(2)
		zoom_height=(1920 * options.zoom).toFixed(2)
		document.documentElement.style.setProperty('--zoomdata',zoom)
		document.documentElement.style.setProperty('--zoom_width',`${zoom_width}px`)
		document.documentElement.style.setProperty('--zoom_height',`${zoom_height}px`)
		console.log(adb_host, adb_port, status_bar_height, window_height, window_width,zoom)
		//console.log('可用宽度:', info.windowWidth, '可用高度:', info.windowHeight);
	})
	onMounted(async () => {
		//window.addEventListener('resize', handleResize);
		console.log('adb_info:', adb_host, adb_port)
		updateLocalKeyboard(`${adb_host}:${adb_port}`,token) //改变当前云手机输入法处理
		initPhone(adb_host, adb_port)
		enterFullscreen()
		var device=document.getElementsByClassName('device-view')
		console.log(device)
	});

	const enterFullscreen = async () => {
		const el = document.documentElement;  // 或者你 `.phone-display` 的 DIV 元素
		if (el.requestFullscreen) {
			await el.requestFullscreen();
		} else if ((el as any).webkitRequestFullscreen) {  // Safari
			await (el as any).webkitRequestFullscreen();
		} else if ((el as any).msRequestFullscreen) {
			await (el as any).msRequestFullscreen();
		}
	};
	const exitFullscreen = async () => {
		if (document.exitFullscreen) {
			await document.exitFullscreen();
		} else if ((document as any).webkitExitFullscreen) {
			await (document as any).webkitExitFullscreen();
		} else if ((document as any).msExitFullscreen) {
			await (document as any).msExitFullscreen();
		}
	};

	const handleExit = async () => {
		await exitFullscreen();
	};
	//调成云手机自带输入法
	const updateLocalKeyboard= async (udid:any,token:any) => {
		const requestData = { udid: udid, type:'phone'};
		try {
			const response = await fetch('https://clp.jtcloud.icu/api/v1/tools/switch_local_keyboard', {
				method: 'POST',
				headers: {
					'Content-Type': 'application/json', // 必须：告诉后端数据格式是JSON
					'Authorization': `Bearer ${token}`
				},
				body: JSON.stringify(requestData), // 数据序列化：JSON转字符串
				credentials: 'include' // 按需添加：跨域时携带Cookie（如不需要可删除）
			});
			// 处理响应：fetch仅网络错误会reject，HTTP错误（404/500等）需手动判断
			if (!response.ok) {
				throw new Error(`请求失败：${response.status} ${response.statusText}`);
			}
		} catch (error) {
			console.error('切换键盘失败:', error);
		}
	}
</script>

<style lang="scss" scoped>
	:deep(.video){
		width: var(--zoom_width) !important;
		height: var(--zoom_height) !important;
	}
	:deep(.video-layer){
		// width: 100% !important;
		width: var(--zoom_width) !important;
		height: var(--zoom_height) !important;
	}
	:deep(.touch-layer){
		// width: 100% !important;
		width: var(--zoom_width) !important;
		height: var(--zoom_height) !important;
		background-color: aqua;
	}
	.body_page {
		width: 100vw;
		height: 100vh;
		background-color: #f5f7fa;
	}

	.phone-display {
		/* flex: 1; */
		// padding: 0px;
		height: 100%;
		width: 100%;
		background: #f5f7fa;
		display: flex;
		align-items: center;
		justify-content: center;
		position: relative;
	}

	:deep(.device-view) {
		display: flex !important;
		flex-direction: column-reverse;
		flex-wrap: nowrap !important;
		align-items: center;

	}

	:deep(.control-buttons-list) {
		width: 100%;
		height: 50px;
		min-height: 50px;
		max-height: 50px;
		z-index: 999;
		background-color: transparent !important;
		svg {
			width: 35px;
			height: 35px;

			&:hover {
				cursor: pointer;
			}
		}
	}

	:deep(.control-button) {
		height: 40px;
		width: 40px;
		min-width: 40px;
		padding: 0px;
		text-align: center;
		border-radius: 6px;
	}

	.floating-toolbar {
		position: fixed;
		top: 10px;
		right: 10px;
		z-index: 1000;
	}

	.floating-toolbar button {
		padding: 0.5rem 1rem;
		font-size: 1rem;
	}
</style>